<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-col><el-button type='primary' @click="addRolesInfo">添加角色</el-button></el-col>
      </el-row>
      <el-table :data="rolesList" border stripe>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row  :class="['bdBottom', index1 === 0 ? 'bdTop' : '', 'vcenter']"  v-for="(item1, index1) in scope.row.children" :key="item1.id">
              <el-col :span="5">
                <el-tag closable @close="deleteRightsById(scope.row, item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <el-row :class="[index2 === 0 ? '' : 'bdTop', 'vcenter']"  :span="19" v-for="(item2, index2) in item1.children" :key="item2.id">
                  <el-col :span="6">
                    <el-tag closable @close="deleteRightsById(scope.row, item2.id)" type="success">{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag type="warning" v-for="item3 in item2.children" :key="item3.id" closable @close="deleteRightsById(scope.row, item3.id)">{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="角色名称" prop='roleName'></el-table-column>
        <el-table-column label="角色描述" prop='roleDesc'></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" icon="el-icon-edit" @click="showEditRoleInfo(scope.row.id)">编辑</el-button>
            <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteRoles(scope.row.id)">删除</el-button>
            <el-button type="warning" size="mini" icon="el-icon-setting" @click="showSetRightsDialog(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色对话框 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addRolesDialog"
      width="30%"
      @close="addRolesDialogClosed">
      <el-form label-width="80px" :model="roleForm" ref="roleRefs" :rules="roleRules">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="roleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRolesDialog = false">取 消</el-button>
        <el-button type="primary" @click="addRolesInfoApi">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑角色对话框 -->
    <el-dialog
      title="编辑角色"
      :visible.sync="editRolesDialog"
      width="30%"
      @close="editRolesDialogClosed">
      <el-form label-width="80px" :model="roleForm" ref="editFormRefs" :rules="roleRules">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="roleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRolesDialog = false">取 消</el-button>
        <el-button type="primary" @click="editRoleDialogInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限的对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightsVisible"
      width="50%" @close="closeRightsVisible">
      <!-- 这是树型控件 data是数据源 props动态绑定的配置选项 -->
      <el-tree ref="treeRef" :data="rigtsList" :props="treeProps" show-checkbox node-key="id" default-expand-all :default-checked-keys="defKeys"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightsVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      rolesList: [],
      addRolesDialog: false,
      roleForm: {},
      roleRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
        ]
      },
      editRolesDialog: false,
      setRightsVisible: false,
      // 这是权限列表的数据
      rigtsList: [],
      // 这是树型属性的动态绑定的配置选项
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      // 树形结构默认 选择id
      defKeys: [],
      roleId: ''
    }
  },
  mounted () {
    this.getRolesList()
  },
  methods: {
    async getRolesList () {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取用户角色失败')
      this.rolesList = res.data
      console.log(this.rolesList)
    },
    addRolesInfo () {
      this.addRolesDialog = true
    },
    addRolesDialogClosed () {
      this.$refs.roleRefs.resetFields()
    },
    addRolesInfoApi () {
      // 表单预验证
      this.$refs.roleRefs.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('roles', this.roleForm)
        if (res.meta.status !== 201) return this.$message.error('添加角色失败')
        this.addRolesDialog = false
        this.$message.success('添加角色成功')
        this.getRolesList()
      })
    },
    // 删除角色
    async deleteRoles (id) {
      // 在删除之前需要提示是否删除的信息
      const messageBox = await this.$confirm('此操作将永久删除该用户角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (messageBox === 'cancel') return this.$message.info('你已经取消了删除操作')
      const { data: res } = await this.$http.delete('roles/' + id)
      if (res.meta.status !== 200) return this.$message.error('删除角色失败')
      this.$message.success('删除角色成功')
      this.getRolesList()
    },
    editRolesDialogClosed () {
      this.editRolesDialog = false
    },
    // 显示编辑角色对话框
    async showEditRoleInfo (id) {
      console.log(id)
      const { data: res } = await this.$http.get('roles/' + id)
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error('查询用户角色失败')
      this.roleForm = res.data
      this.editRolesDialog = true
    },
    editRoleDialogInfo () {
      this.$refs.editFormRefs.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put('roles/' + this.roleForm.roleId, {
          roleName: this.roleForm.roleName,
          roleDesc: this.roleForm.roleDesc
        })
        console.log(res)
        if (res.meta.status !== 200) return this.$message.error('表单修改失败')
        this.editRolesDialog = false
        this.getRolesList()
        this.$message.success('表单修改成功')
      })
    },
    // 通过id删除角色的某个权限
    async deleteRightsById (role, rigthsId) {
      const confirmResult = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') return this.$message.info('取消了这次权限删除')
      // console.log('确认了删除')
      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rigthsId}`)
      if (res.meta.status !== 200) return this.$message.error('删除角色权限失败')
      this.$message.success('删除权限成功')
      role.children = res.data
    },
    // 展示分配权限的对话框
    async showSetRightsDialog (role) {
      // 在显示这个对话框的时候，先绑定的当前角色的id，已被后续处理
      this.roleId = role.id
      // 在显示对话框之前，先要获取权限的数据
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error('获取权限失败')
      // console.log(res.data)
      this.rigtsList = res.data
      // 将三级节点赋值给树形节点的数组中去
      this.getNode(role, this.defKeys)
      this.setRightsVisible = true
    },
    // 通过递归的方式将三级权限的id拿到，并赋值给数型节点的数组里面去
    getNode (node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getNode(item, arr)
      })
    },
    closeRightsVisible () {
      this.defKeys = []
    },
    async allotRights () {
      const keys = [
        // getCheckedKeys返回被选中节点的数组
        ...this.$refs.treeRef.getCheckedKeys(),
        // getHalfCheckedKeys返回半选中节点的数组
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      // console.log(key)
      const idStr = keys.join(',')
      // console.log(idStr)
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error('更新权限角色失败')
      this.$message.success('更新角色权限成功')
      this.getRolesList()
      this.setRightsVisible = false
    }
  }
}
</script>

<style lang="less" scoped>

</style>
